package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.templates.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.Like;
import com.tanhua.domain.vo.ContractVo;
import com.tanhua.domain.vo.LikeVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.UserInfoVo;
import com.tanhua.dubbo.api.*;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IMService {

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private QuestionApi questionApi;

    @Reference
    private FriendApi friendApi;

    @Reference
    private LikeApi likeApi;

    @Reference
    private CommentApi commentApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    //查询环信用户信息
    public ResponseEntity<Object> queryUserInfo(Long huanxinId) throws InvocationTargetException, IllegalAccessException {
        UserInfo userInfo = userInfoApi.findById(huanxinId);
        UserInfoVo userInfoVo = new UserInfoVo();
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfoVo, userInfo);

            userInfoVo.setAge(userInfo.getAge().toString());
        }

        return ResponseEntity.ok(userInfoVo);
    }

    //回答陌生人问题
    public ResponseEntity<Object> strangeQuestionsReply(Integer userId, String reply) {
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());

        Question question = questionApi.findByUid(userId.longValue());

        Map<String, Object> map = new HashMap<>();
        map.put("userId", userInfo.getId());
        map.put("strangerQuestion", question != null ? question.getTxt() : "你喜欢什么？");
        map.put("nickname", userInfo.getNickname());
        map.put("reply", reply);

        String result = JSON.toJSONString(map);

        huanXinTemplate.sendMsg(userId.toString(),result);

        return ResponseEntity.ok(null);
    }

    //添加联系人业务
    public ResponseEntity<Object> addContacts(Integer friendId) {
        Long uid = UserHolder.getUserId();

        huanXinTemplate.contactUsers(uid,friendId.longValue() );

        Friend friend1 = new Friend();
        friend1.setUserId(friendId.longValue());
        friend1.setFriendId(uid);
        friend1.setCreated(System.currentTimeMillis());

        Friend friend2 = new Friend();
        friend2.setUserId(uid);
        friend2.setFriendId(friendId.longValue());
        friend2.setCreated(System.currentTimeMillis());

        friendApi.save(friend1,friend2);
        return ResponseEntity.ok(null);
    }

    //好友列表业务
    public ResponseEntity<Object> showContacts(Integer page, Integer pagesize, String keyword) throws InvocationTargetException, IllegalAccessException {
        PageResult pageResult = friendApi.queryFriends(page,pagesize,UserHolder.getUserId(), keyword);
        List<Friend> items = (List<Friend>) pageResult.getItems();
        List<ContractVo> list = new ArrayList<>();

        if(items != null){
            for (Friend item : items) {
                UserInfo userInfo = userInfoApi.findById(item.getFriendId());
                if(!StringUtils.isAllEmpty(keyword)&&!userInfo.getNickname().contains(keyword)){
                    continue;
                }
                ContractVo contractVo = new ContractVo();

                BeanUtils.copyProperties(contractVo,userInfo);
                contractVo.setUserId(userInfo.getId().toString());
                contractVo.setCity(StringUtils.substringBefore(userInfo.getCity(),"-"));
                list.add(contractVo);
            }
        }

        pageResult.setItems(list);
        return ResponseEntity.ok(pageResult);
    }

    //显示点赞、评论、喜欢列表业务
    public ResponseEntity<Object> getList(Integer page, Integer pagesize,Integer contentType) throws InvocationTargetException, IllegalAccessException {
        PageResult pageResult = commentApi.queryByUser(page,pagesize,UserHolder.getUserId(),contentType);
        List<Comment> items = (List<Comment>) pageResult.getItems();
        ArrayList<LikeVo> likeVos = new ArrayList<>();
        if(items != null){
            for (Comment item : items) {
                LikeVo likeVo = new LikeVo();
                UserInfo userInfo = userInfoApi.findById(item.getUserId());
                BeanUtils.copyProperties(likeVo,userInfo);
                likeVo.setId(userInfo.getId().toString());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:DD");
                likeVo.setCreateDate(sdf.format(userInfo.getCreated()));
                likeVos.add(likeVo);
            }
        }
        pageResult.setItems(likeVos);
        return ResponseEntity.ok(pageResult);
    }

}
